﻿using System.Configuration;

namespace AiMachineControl.Model
{
    public class ConfigHelper
    {
        /// <summary>
        /// 返回Config文件中对应Key的Val值
        /// </summary>
        /// <param name="str_Key">传入Key名称</param>
        /// <returns>对应Key的Val值</returns>
        public static string GetAppConfig(string str_Key)
        {
            string file = "";// System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == str_Key)
                {
                    return config.AppSettings.Settings[str_Key].Value.ToString();
                }
            }
            return null;


        }
        /// <summary>
        /// 更新Config文件，若Key已存在，替换当前Val值；不存在则添加新的键值对
        /// </summary>
        /// <param name="str_newKey">修改key值的名称</param>
        /// <param name="str_newVal">修改后的值</param>
        public static void UpdateAppConfig(string str_newKey, string str_newVal)
        {
            string file = "";//System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            bool exist = false;
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == str_newKey)
                {
                    exist = true;
                }
            }
            if (exist)
            {
                config.AppSettings.Settings.Remove(str_newKey);
            }
            config.AppSettings.Settings.Add(str_newKey, str_newVal);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");

        }

        
    }
}
